import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login/index.vue'
import Layout from '../views/Layout/index.vue'
// 首页
import Home from '../views/Home/home.vue'
// 内容
import Articles from '../views/Articles/articles.vue'
// 素材
import ImageOne from '../views/Image/image.vue'
// 发布文章
import PublishedArticle from '../views/PublishedArticle/publishedArticle.vue'
// 评论管理
import Comment from '../views/Comments/comment.vue'
// 粉丝管理
import Fans from '../views/Fans/fans.vue'
// 个人设置
import Settings from '../views/Settings/settings.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      { path: '/', name: 'home', component: Home },
      { path: 'articles', name: 'articles', component: Articles },
      { path: 'image', name: 'imageOne', component: ImageOne },
      { path: 'publishedArticle', name: 'publishedArticle', component: PublishedArticle },
      { path: 'comment', name: 'comment', component: Comment },
      { path: 'fans', name: 'fans', component: Fans },
      { path: 'settings', name: 'settings', component: Settings }

    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]
const router = new VueRouter({
  routes
})

// 重点：
// 需要把获取token放到函数里面，保证每次都获取新的token

// const token = window.localStorage.getItem('token')
// 如下页面是需要登陆之后才能访问的
const authPageList = ['/', '/articles', '/images', '/xxxxx']

router.beforeEach((to, from, next) => {
  console.log('发生了路由变化', from.path, '到', to.path)
  // 如果你要去的页面是主页，而你又没有登陆，则回到登陆页
  // if (to.path === '/' || to.path === '/articles') {
  if (authPageList.includes(to.path)) {
    if (localStorage.getItem('token')) {
      next()
    } else {
      console.log('你要去的是主页，但是你并没有登陆，所以路由导航守卫把你送到的Login')
      // 如果没有 token 就回到登录页面，并携带一个从哪个页面来的地址
      next('/login?redirect=' + to.path)
    }
  } else {
    next()
  }
})

export default router
